#!/usr/bin/env python3

# Written by Pedro Gimeno
# args: infile outfile savename

import sys, struct

def main():
  if len(sys.argv) < 4:
    sys.stderr.write("Usage: bas2cas.py infile outfile filename6chars\n")
    return

  h = b'\x1F\xA6\xDE\xBA\xCC\x13\x7D\x74'
  if sys.argv[1] != '-':
    f = open(sys.argv[1], 'rb')
    try:
      data = f.read()
    finally:
      f.close()
  else:
    data = sys.stdin.buffer.read()

  # Pad it to a multiple of 256 bytes, adding at least one EOF
  data += b'\x1A'
  data += b'\x1A' * (-len(data) % 256)

  # Not the right encoding, so just in case, don't use special characters
  nam = ('%-6.6s' % sys.argv[3]).encode('latin1')

  if sys.argv[2] != '-':
    g = open(sys.argv[2], 'wb')
  else:
    g = sys.stdout.buffer
  try:
    # Block 1 (header)
    g.write(h)
    g.write(b'\xEA' * 10)
    g.write(nam)

    # Subsequent blocks
    for i in range(0, len(data), 256):
      g.write(h)
      g.write(data[i:i+256])
  finally:
    if sys.argv[2] != '-':
      g.close()

main()
